var m_maps;
var all_popkart_maps;
var probability;
var all_maps_array = new Array();
var item_maps_array = new Array();
var allow_maps = new Array();
var selected_maps = new Array();

var shuffled_maps = new Array();
var pos = 0
const MAX_MAPS_COUNT = 20
const cookie_map = "maps"
const cookie_pos = "pos"
const cookie_allow_maps = "allow_maps"
const cookie_banned_maps = "banned_maps"

//获取设备
var getEQ = function () {
    var ua = navigator.userAgent; //获取浏览器UA
    isWindowsPhone = /(?:Windows Phone)/.test(ua),
        isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
        isAndroid = /(?:Android)/.test(ua),
        isFireFox = /(?:Firefox)/.test(ua),
        isChrome = /(?:Chrome|CriOS)/.test(ua),
        isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
        isPhone = /(?:iPhone)/.test(ua) && !isTablet,
        isPc = !isPhone && !isAndroid && !isSymbian;
    return {
        isTablet: isTablet,
        isPhone: isPhone,
        isAndroid: isAndroid,
        isPc: isPc
    };
}

function init() {
    function on_load_show() {
        if (checkCookie() == true) {
            loadLastMaps();
            showMenu2();
        }
        else {
            showMenu1();
        }
        show();
        showBannedList();
    }
    getUrl("data/maps.json", function (text) {
        m_maps = JSON.parse(text);
        for (var i in m_maps) {
            for (let j of m_maps[i]) {
                all_maps_array.push(j);
            }
        }
    });
    getUrl("data/probability.json", function (text) { probability = JSON.parse(text); });
    getUrl("data/all_maps.json", function (text) { all_popkart_maps = JSON.parse(text); showBanList(); });
    getUrl("data/item_maps.json", function (text) { item_maps_array = JSON.parse(text); });
    on_load_show();
}

Array.prototype.shuffle = function () {
    var input = this; for (var i = input.length - 1; i >= 0; i--) { var randomIndex = Math.floor(Math.random() * (i + 1)); var itemAtIndex = input[randomIndex]; input[randomIndex] = input[i]; input[i] = itemAtIndex; } return input;
}

function getUrl(url, f) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', url, true);
    httpRequest.send();
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            var text = httpRequest.responseText;
            f(text);
        }
    };
}

function genMapPoolsByMode(mode) {
    function getMaps(m) {
        var arr = new Array();
        for (var i in m) {
            var tmp = getRandomMaps(m_maps[i], m[i] * MAX_MAPS_COUNT)
            arr = arr.concat(tmp);
        }
        return arr;
    }
    var arr = new Array();
    if (mode in probability) {
        allow_maps = getMaps(probability[mode]);
    }
    else {
        if (mode == "hell") {
            allow_maps = genHellMapPools();
        }
        else if (mode == "all") {
            allow_maps = genAllMapPools();
        }
        else if (mode == "item") {
            allow_maps = genItemMapPools();
        }
    }

}

function genItemMapPools() {
    return getRandomMaps(item_maps_array, MAX_MAPS_COUNT);
}

function genAllMapPools() {
    return getRandomMaps(all_maps_array, MAX_MAPS_COUNT);
}

function genHellMapPools() {
    var a = new Array();
    a = getRandomMaps(m_maps["l1"], MAX_MAPS_COUNT)
    a = a.concat(getRandomMaps(m_maps["l2"], MAX_MAPS_COUNT - a.length));
    return a
}

function getRandomMaps(arr, count) {
    var tmp = arr.concat()
    var list = new Set(JSON.parse(getCookie(cookie_banned_maps)));
    for (var i = tmp.length - 1; i >= 0; i--) {
        if (list.has(arr[i])) {
            tmp.splice(i, 1);
        }
    }
    return genRandomArray(tmp, count);
}

function genRandomArray(arr, count) {
    if (count > arr.length) {
        count = arr.length;
    }
    var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}

function setCookie(key, value) {
    localStorage.setItem(key, value);
}

function getCookie(key) {
    return localStorage.getItem(key);;
}

function delCookie(key) {
    return localStorage.removeItem(key);;
}

function checkCookie() {
    if (getCookie(cookie_allow_maps))
        return true;
    else
        return false;
}

function clearCookie() {
    delCookie(cookie_allow_maps);
    delCookie(cookie_map);
    delCookie(cookie_pos);
}

function getMapArchive(s) {
    for (var i in all_popkart_maps) {
        console.log(typeof all_popkart_maps[i])
        if (all_popkart_maps[i].indexOf(s) != -1) {
            return i;
        }
    }
    return false;
}

function loadLastMaps() {
    allow_maps = JSON.parse(getCookie(cookie_allow_maps));
    shuffled_maps = JSON.parse(getCookie(cookie_map));
    pos = parseInt(JSON.parse(getCookie(cookie_pos)));
    if (pos <= shuffled_maps.length) {
        for (var i = 0; i < pos; ++i) {
            var next_map = shuffled_maps[i];
            var index = allow_maps.indexOf(next_map);
            allow_maps.splice(index, 1);
            selected_maps.push(next_map);
        }
    }
    else {
        throw new Error("Cookie Error");
    }
}

function genMode() {
}

function on_mode(mode) {
    genMapPoolsByMode(mode);
    shuffled_maps = allow_maps.concat();
    shuffled_maps.shuffle();
    pos = 0;
    setCookie(cookie_allow_maps, JSON.stringify(allow_maps));
    setCookie(cookie_map, JSON.stringify(shuffled_maps));
    setCookie(cookie_pos, pos);
    showMenu2();
    show();
}

function on_next() {
    if (pos == shuffled_maps.length) {
        alert("莫得了");
    }
    else {
        var next_map = shuffled_maps[pos];
        var index = allow_maps.indexOf(next_map);
        allow_maps.splice(index, 1);
        selected_maps.push(next_map);
        setCookie(cookie_pos, ++pos);
        var s = getMapArchive(next_map);
        var obj = document.getElementById("next_map_id");
        if (s) {
            next_map = next_map + "【属于" + s + "级地图】";
        }
        obj.innerHTML = next_map;
        show();
    }
}

function on_reset() {
    allow_maps = new Array();
    selected_maps = new Array();
    shuffled_maps = new Array();
    pos = 0;
    clearCookie();
    var obj = document.getElementById("next_map_id");
    obj.innerHTML = "";
    showMenu1();
    show();
}

function show() {
    var s = "";
    var obj = document.getElementById("allow_map_id");
    for (let i of allow_maps) {
        s = s + "<li>" + i + "</li>";
    }
    obj.innerHTML = s;
    obj = document.getElementById("selected_map_id");
    s = "";
    for (let i of selected_maps) {
        s = s + "<li>" + i + "</li>";
    }
    obj.innerHTML = s;
}

function showMenu1() {
    document.getElementById('main_btn').style.display = 'none';
    document.getElementById('mode_btn').style.display = 'block';
}

function showMenu2() {
    document.getElementById('main_btn').style.display = 'block';
    document.getElementById('mode_btn').style.display = 'none';
}

function showBannedList() {
    var arr = JSON.parse(getCookie(cookie_banned_maps));
    if (arr) {
        var obj = document.getElementById("banned_list_id");
        var s = "";
        for (var i = 0; i < arr.length; ++i) {
            s += '<li><input id="banCkb' + i + '"type="checkbox" name="del_ban_map_box" value="' + arr[i] + '"><label for="banCkb' + i + '">' + arr[i] + '</label></li>'
        }
        obj.innerHTML = s;
    }
}

function showBanList() {
    var arr1 = new Array();
    for (var i in all_popkart_maps) {
        arr1 = arr1.concat(all_popkart_maps[i])
    }
    var arr2 = JSON.parse(getCookie(cookie_banned_maps));
    if (arr2 && arr2.length > 0) {
        var arr1 = arr1.filter(el => !arr2.includes(el))
    }
    var obj = document.getElementById("ban_list_id");
    var s = "";
    for (var i = 0; i < arr1.length; ++i) {
        s += '<li><input id="bannedCkb' + i + '"type="checkbox" name="ban_map_box" value="' + arr1[i] + '"><label for="bannedCkb' + i + '">' + arr1[i] + '</label></li>'
    }
    obj.innerHTML = s;
}

function on_ban_btn() {
    var arr = new Set(JSON.parse(getCookie(cookie_banned_maps)));
    var items = document.getElementsByName("ban_map_box");
    for (i = 0; i < items.length; i++) {
        if (items[i].checked) {
            arr.add(items[i].value);
        }
    }
    setCookie(cookie_banned_maps, JSON.stringify(Array.from(arr)));
    showBanList();
    showBannedList();
    document.getElementById("top_bar_id").scrollIntoView();
}

function on_del_ban_btn() {
    var arr = new Set(JSON.parse(getCookie(cookie_banned_maps)));
    var items = document.getElementsByName("del_ban_map_box");
    for (i = 0; i < items.length; i++) {
        if (items[i].checked) {
            if (arr.has(items[i].value)) {
                arr.delete(items[i].value);
            }
        }
    }
    setCookie(cookie_banned_maps, JSON.stringify(Array.from(arr)));
    showBanList();
    showBannedList();
    document.getElementById("top_bar_id").scrollIntoView();
}


window.onload = function () {
    init();

}
